//
//  BlogCell.swift
//  mmda
//
//  Created by 李陆涛 on 2018/8/3.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import YYText

enum ActionType {
    case comment
    case like
    case map
    case auth
}

protocol BlogCellDelegagte: NSObjectProtocol {
    
    func blogCell(cell:BlogCell,userid:Int?)
    
    func blogCell(cell:BlogCell, action:ActionType, blog:Blog)
    
    func blogCell(cell:BlogCell, need present:UIViewController)
}

class BlogCell: UITableViewCell {

    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var onlineTimeLabel: UILabel!
    @IBOutlet weak var blogContentLabel: UILabel!
    @IBOutlet weak var authBtn: UIButton!
    
//    @IBOutlet weak var collectionView: UICollectionView!
//
//    @IBOutlet weak var collectionViewH: NSLayoutConstraint!
    
    @IBOutlet weak var funcView: UIView!
    @IBOutlet weak var funcViewH: NSLayoutConstraint!
    @IBOutlet weak var commentBtn: UIButton!
    
    @IBOutlet weak var likeBtn: UIButton!
    @IBOutlet weak var mapBtn: UIButton!
    
    @IBOutlet weak var picView: PictureView!
    
    @IBOutlet weak var praiseBGView: UIView!
    @IBOutlet weak var praiseView: YYLabel!
    
    @IBOutlet weak var praiseViewH: NSLayoutConstraint!
    @IBOutlet weak var praiseViewTop: NSLayoutConstraint!
    @IBOutlet weak var praiseViewBottom: NSLayoutConstraint!
    
    var reloadCell:((BlogCell)->Void)?
    
    
    var funcViewHidden:Bool = false {
        
        didSet {
            
            if funcViewHidden {
                
                funcView.isHidden = true
                funcViewH.constant = 0
            }
        }
    }
    
    private var isPraiseViewHidden:Bool = false {
        
        willSet {
            
            if newValue {
                
                praiseView.textContainerInset = UIEdgeInsets.zero
                praiseViewTop.constant = 0
                praiseViewBottom.constant = 0
                praiseViewH.constant = 0
                praiseBGView.isHidden = true
            } else {
                
                praiseViewTop.constant = 8
                praiseViewBottom.constant = 8
                
                praiseBGView.isHidden = false
            }
            
            if isPraiseViewHidden != newValue {
                
                self.reloadCell?(self)
            }
        }
    }
    
    weak var delegate: BlogCellDelegagte?
    
    
    private var blog:Blog?
    
    override func awakeFromNib() {
        super.awakeFromNib()

        praiseView.numberOfLines = 0
        praiseView.preferredMaxLayoutWidth = CGFloat(kScreenWidth - 48)
    }
    
    func setBlog(_ blog:Blog) {
        
        self.blog = blog
        
        userImageView.setImage(string: blog.user_info?.logo_new?.getQiniuThumb(thumbImageWidth), placeholder: #imageLiteral(resourceName: "default"))
        userNameLabel.text = blog.user_info?.nickname
        onlineTimeLabel.text = blog.update_at?.leftTimeStringWithFormat("MM-dd HH:mm")
        blogContentLabel.text = blog.remark
        picView.setBlog(blog)
        picView.delegate = self
        
        
        if blog.user_id == AppManager.share.user?._id {
            
            if blog.status == 0 {
                
                self.authBtn.setTitle("公开", for: .normal)
                self.authBtn.setImage(#imageLiteral(resourceName: "all"), for: .normal)
            } else {
                
                self.authBtn.setTitle("仅自己可见", for: .normal)
                self.authBtn.setImage(#imageLiteral(resourceName: "self"), for: .normal)
            }
        } else {
            
            self.authBtn.setTitle(nil, for: .normal)
            self.authBtn.setImage(#imageLiteral(resourceName: "展 开"), for: .normal)
        }
        
        
        likeBtn.setTitle("点赞", for: .normal)
        likeBtn.setTitleColor(UIColor.darkGray, for: .normal)
        
        if let likeCount = blog.praise_count {
            
            if likeCount > 0 {
                
                likeBtn.setTitle("\(likeCount)", for: .normal)
                
            }
        }
        
        likeBtn.setImage(#imageLiteral(resourceName: "点赞"), for: .normal)
        
        if let liked = blog.is_praise {
            
            if liked {
                likeBtn.setImage(#imageLiteral(resourceName: "点赞2"), for: .normal)
                likeBtn.setTitleColor(UIColor.red, for: .normal)
            }
        }
        
        
        commentBtn.setTitle("评论", for: .normal)
        
        if let commentCount = blog.comment_count {
            
            if commentCount > 0 {
                
                commentBtn.setTitle("\(commentCount)", for: .normal)
            }
        }
        
        reloadPrasieView()
    }
    
    private func reloadPrasieView() {
        
        guard let praises = blog?.praise else {
            
            praiseView.text = nil
            isPraiseViewHidden = true
            return
        }
        
        if praises.count == 0 {
            
            praiseView.text = nil
            isPraiseViewHidden = true
            return
        }

        isPraiseViewHidden = false
        let attstr = NSMutableAttributedString()
        
        let image = #imageLiteral(resourceName: "点赞")
        
        let attachment = NSMutableAttributedString.yy_attachmentString(withEmojiImage: image, fontSize: 14)
        
        attstr.append(attachment!)
        attstr.yy_appendString("\t")
        
        
        for praise in praises {
            
            guard let nickName = praise.praise_user_info?.nickname else { return }
            
            let str = NSMutableAttributedString(string: nickName)
            
            //            let heightlight = YYTextHighlight(backgroundColor: kBlue)
            
            str.yy_setTextHighlight(str.yy_rangeOfAll(), color: kBlue, backgroundColor: nil) { _,_,_,_ in
                
                self.delegate?.blogCell(cell: self, userid: praise.praise_user_info?._id)
            }
            
            attstr.append(str)
            if praises.last!._id != praise._id {
                
                attstr.yy_appendString("，")
            }
        }
        
        praiseView.attributedText = attstr
        
        let height = YYTextLayout(containerSize: CGSize(width: kScreenWidth - 32, height: Int.max), text: attstr)?.textBoundingSize.height ?? 0
        
        self.praiseViewH.constant = height + 10
    }
    

    @IBAction func userAction(_ sender: Any) {
    
        delegate?.blogCell(cell: self, userid: blog?.user_info?._id)
    }
    
    @IBAction func funcAction(_ sender: UIButton) {
        
        if mapBtn == sender {// 地图
            
            delegate?.blogCell(cell: self, action: .map, blog: blog!)
            
            return
        }
        
        if likeBtn == sender {
            
            
            changeLikeState()
            likeAnimation()
            
            NetAPI.touch(bid: blog!._id!, status: blog!.is_praise! ? 10 : 11).request {
                [weak self] response, errmsg in
                guard let `self` = self else { return }
                
                if let _ = errmsg {
                    
                    self.changeLikeState()
                }
                
            }
            
            delegate?.blogCell(cell: self, action: .like, blog: blog!)
            
            return
        }
        
        if commentBtn == sender {
            
            delegate?.blogCell(cell: self, action: .comment, blog: blog!)
            
            return
        }
        
        if authBtn == sender {
            
            delegate?.blogCell(cell: self, action: .auth, blog: blog!)
            
            return
        }
    }
    
    private func changeLikeState() {
        
        
        guard let blog = self.blog else { return }
        
        if blog.is_praise ?? false {
            
            blog.praise_count = max((self.blog!.praise_count ?? 0) - 1, 0);
            blog.is_praise = false
            
            if var oldArray = blog.praise {
                
                if let index = oldArray.index(where: { (praise) -> Bool in
                    
                    return praise.praise_user_info?._id == AppManager.share.user?._id
                }) {
                    
                    print("index ========== \(index)")
                    
                    oldArray.remove(at: index)
                    blog.praise = oldArray
                }
            }
            
        } else {
            
            blog.praise_count = (blog.praise_count ?? 0) + 1;
            blog.is_praise = true
            
            let praise = Praise()
            praise.praise_user_info = AppManager.share.user
            
            var array = [praise]
            
            if let oldArray = blog.praise {
                
                array += oldArray
            }
            
            blog.praise = array
        }

        self.setBlog(blog)
    }
    
    private func likeAnimation() {
        
        let animation = CABasicAnimation(keyPath: "transform.scale")
        
        animation.fromValue = 1.0
        animation.toValue = 1.5
        animation.duration = 0.25
        animation.repeatCount = 1
        animation.isRemovedOnCompletion = true
        animation.autoreverses = true
        
        likeBtn.layer.add(animation, forKey: nil)
    }
    
}

extension BlogCell : PictureViewDelegate {
    
    func pictureView(pictureView:PictureView,didSelectItem:UIImageView,index:Int) {
        
        guard let blog = self.blog else { return }
        
        
        if let videocount = blog.videos?.count {
            
            if videocount > index {
                
                guard let urlstr = blog.videos?[index].video_url else { return }
                
                let videoVC = LLTVideoPlayerVC()
                
                let url = URL(string: urlstr)
                videoVC.videoURL = url
                
                delegate?.blogCell(cell: self, need: videoVC)
                
                return
            }
        }
        
        guard let picarray = blog.pictures_new else { return }
        
        
        var images = [SKPhoto]()
        
        for url in picarray {
            
            let placeholder = UIImageView.imageCache(for: url.getQiniuThumb(thumbImageWidth))
            
            
            if let p = placeholder, p.isGIF() {
                
                let photo = SKPhoto.photoWithImage(p)
                images.append(photo)
            } else {
                
                let photo = SKPhoto.photoWithImageURL(url, holder: placeholder)
                photo.shouldCachePhotoURLImage = true
                images.append(photo)
            }
        }
        
        SKPhotoBrowserOptions.displayAction = true
        SKPhotoBrowserOptions.displayStatusbar = true
        SKPhotoBrowserOptions.displayCounterLabel = true
        SKPhotoBrowserOptions.displayBackAndForwardButton = true
        SKPhotoBrowserOptions.enableSingleTapDismiss = true
        
        let browser = SKPhotoBrowser(photos: images, initialPageIndex: index)
        browser.cancelTitle = "取消"
        browser.delegate = self
        browser.statusBarStyle = .lightContent
        
        delegate?.blogCell(cell: self, need: browser)
    }
}


extension BlogCell: SKPhotoBrowserDelegate {
    
    func viewForPhoto(_ browser: SKPhotoBrowser, index: Int) -> UIView? {
        
        return self.picView.subviews[index]
    }
}


extension BlogCell {
    
    class func calcHeight(_ blog:Blog) -> CGFloat {
        
        let labelH = blog.remark?.getHeight(font: kFont12!, width: CGFloat(kScreenWidth - 32))
        
        
        var count = blog.pictures_new?.count ?? 0
        
        if let videocount = blog.videos?.count {
            
            if videocount > 0 {
                
                count = videocount
            }
        }
        
        let width = CGFloat(kScreenWidth - 48) / 3.0
        
        let lines = ceil(CGFloat(count) / 3.0)
        
        let viewH = lines * width + 10 * (lines - 1)
        
        return 124 + labelH! + viewH
    }
}
